package com.briup.run.web.listener;

import com.briup.run.bean.Memberinfo;
import com.briup.run.service.MemberInfoService;
import com.briup.run.service.impl.MemberInfoServiceImpl;
import com.briup.run.util.IpUtil;

import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.util.List;

/**
 * @Auther: vanse(lc))
 * @Date: 2022/10/11-10-11-9:42
 * @Description：监听登录后的动作 (观察者模式)
 */
@WebListener
public class LoginSessionListener implements HttpSessionAttributeListener, ServletRequestListener {
    HttpServletRequest request;

    // 登录的逻辑就是在session中添加了属性 memberinfo
    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        HttpSession session = event.getSession();
        String name = event.getName();  // key值 memberinfo
//        System.out.println("name = " + name);
        if ("memberinfo".equals(name)) {
            // 监听的动作
            MemberInfoService memberInfoService = new MemberInfoServiceImpl();
            // 在线人数
            long countOnLine = memberInfoService.countOnLine();
            // 前10名数据
            List<Memberinfo> beforeNumList = memberInfoService.beforeNumMemberInfo(10);
            session.setAttribute("countOnLine", countOnLine);
            session.setAttribute("beforeNumList", beforeNumList);
            String readIp = IpUtil.getReadAdd(IpUtil.getIpAddr(request));
            session.setAttribute("readIp", readIp);
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {

    }

    @Override
    public void attributeReplaced(HttpSessionBindingEvent event) {

    }

    // 监听request销毁
    @Override
    public void requestDestroyed(ServletRequestEvent sre) {

    }

    // 监听request创建
    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        request = (HttpServletRequest) sre.getServletRequest();
    }
}
